<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<style>
    .table-bordered, .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
        border: 1px solid #dcdcdc;
    }

    .productrow {
        clear: both;
        display: block;
    }

    .proimg {
        float: left;
        text-align: center;
        margin-right: 4px;
    }

    .proimg img {
        width: 90px;
        border: 1px solid #ddd;
        display: block;
    }

    /*定义类名为.thead-blue的样式*/
    .table .thead-blue th {
        color: #fff;
        background-color: #3c8dbc;
    }
</style>
<div class="row">
    <div class="col-sm-12">
        <div class="box">
            <div class="box-header with-border">
                <h2 class="page-header">
                    <i class="fa fa-globe"></i> 所有询盘
                </h2>
            </div>
            <div class="box-body">
                <div class="mb-10">
                    <?php echo form_open(current_url(), array('class' => 'form-inline', 'method' => 'get', 'id' => 'search_goods')); ?>
                    <div class="form-group" style="margin-right:15px;">
                        <select class="form-control" name="sitetype">
                            <option value="0">所有类型</option>
                            <?php foreach ($sitetype as $k => $s): ?>
                                <option value="<?php echo $k; ?>"><?php echo $s; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>


                    <div class="form-group" style="margin-right:15px;">
                        <select class="form-control" name="state">
                            <option value="0">所有站点</option>
                            <?php foreach ($sindex as $k => $s): ?>
                                <option value="<?php echo $k; ?>" <?php if ($k == $state) echo " selected"; ?>><?php echo $s; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>


                    <div class="form-group" style="margin-right:15px;">
                        <?php echo form_input($keyword); ?>
                    </div>

                    <div class="form-group" style="margin-right:15px;">
                        <?php echo tpl_form_field_daterange("timelimit", ["start" => date("Y-m-d", strtotime("-365 days")), "end" => date("Y-m-d")], false); ?>
                    </div>

                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-sm btn-primary btn-flat', 'content' => "搜索询盘")); ?>
                    <span class="btn btn-flat btn-info btn-sm" id="export">导出订单</span>
                        <?php echo form_close(); ?>
                </div>
                <?php if ($loglist): ?>
                    <table class="table table-bordered table-hover table-dark" style="margin-top:20px;">
                        <thead class="thead-blue">
                        <tr>
                            <th>站点</th>
                            <th>真实姓名</th>
                            <th>邮箱</th>
                            <th>电话</th>
                            <th>数量</th>
                            <th width="350">留言</th>
                            <th>时间</th>
                            <th>ip地址</th>
                            <th>国家</th>
                            <th>来源</th>
                            <th>备注</th>
                            <th width="60" style="text-align: center">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($loglist as $item): ?>
                            <tr shopid="<?php echo $item["id"]; ?>">
                                <td>
                                    <a href="/backend/sites/order/index/<?php echo $item["siteid"]; ?>"
                                       target="_blank"><?php echo $sindex[$item["siteid"]]; ?></a>
                                </td>
                                <td>
                                    <?php
                                    if (ismobile($item["agent"])) {
                                        echo '<i class="fa fa-phone-square" aria-hidden="true"></i>';
                                    } else {

                                    }
                                    ?><?php echo $item["realname"]; ?>
                                </td>
                                <td>
                                    <span class="btn btn-sm btn-forward" itemid="<?php echo $item['realname']; ?>" mail="<?php echo $item['email']; ?>"><i class="fa fa-mail-forward" aria-hidden="true"></i></span><?php echo $item["email"]; ?>
                                </td>
                                <td>
                                    <?php echo $item["phone"]; ?>
                                </td>
                                <td>
                                    <?php
                                    if ($item["quantity"]) {
                                        echo $item["quantity"];
                                    } else {
                                        echo '无';
                                    } ?>
                                </td>
                                <td width="">
                                    <?php echo $item["info"]; ?>
                                </td>
<!--                                <td>--><?php //echo date("Y-m-d H:i", strtotime($item["addtime"])); ?><!--</td>-->
                                <td><?php echo date("Y-m-d H:i", strtotime($item["addtime"])); ?></td>
                                <td>
                                    <a href="https://ip.tool.chinaz.com/<?php echo $item["ipaddr"]; ?>" target="_blank"><?php echo $item["ipaddr"]; ?></a>
                                </td>
                                <td>
                                    <?php echo $item["country"]; ?>
                                </td>
                                <td>
                                    <?php switch (inquiry_source($item["url"])){
                                        case 'product-item':
                                            echo '<a href="' . $item["url"] . '" target="_blank">产品<a/>';
                                            break;
                                        case 'products':
                                            echo '<a href="' . $item["url"] . '" target="_blank">列表<a/>';
                                            break;
                                        case 'FAQ':
                                            echo 'FAQ';
                                            break;
                                        case 'Home':
                                            echo '首页';
                                            break;
                                        case 'about':
                                            echo '关于';
                                            break;
                                        case 'contact':
                                            echo '联络';
                                            break;
                                    }
                                    ?>
                                </td>
                                <td cid="<?php echo $item["id"]; ?>"><span
                                            ondblclick="edit(this,'note');" <?php if ($item["note"]) echo 'style="color:red;"'; ?>><?php echo $item["note"] ? htmlentities($item["note"]) : "备注"; ?></span>
                                </td>
                                <td>
                                    <span class="btn btn-xs btn-flat btn-danger btn-delete" itemid="<?php echo $item["id"] ;?>">
                                        <i class="fa fa-trash-o fa-lg"></i>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
                <?php
                if (empty($loglist)) {
                    echo "<h2 style='text-align:center;padding:50px 0;'>没有查询到数据</h2>";
                }
                ?>
                <?php echo $pager; ?>
                <div class=" pull-right form-inline" style="line-height:30px;margin-top:25px;">
                    <?php echo '共' . $total . '条记录，' . $page . '/' . $pages . '页'; ?>
                    <select id="pagesize" class="form-control input-sm" style="height:22px;">
                        <option value="0">每页数量</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="200">200</option>
                        <option value="500">500</option>
                    </select>
                    <input type="text" id="topage" value="" class="form-control input-sm" placeholder='页码'
                           style="margin:0 5px;height:22px;width:45px;">
                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-xs btn-primary btn-flat', 'id' => 'jumpbtn', 'content' => "跳转")); ?>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/assets/backend/lazyload.js?v=1.9.1"></script>
<script>
    $(document).ready(function () {
        $("img.lazy").lazyload({effect: "fadeIn"});
        requirejs.config({
            paths: {
                jquery: "../../components/jquery/jquery.min",
                viewer: "../../components/viewer/viewer.min",
            },
            shim: {
                viewer: {deps: ["loadcss!../../components/viewer/viewer.min.css"]},
            }
        });
        require(['jquery', 'viewer'], function ($) {
            $('.imgcol img').viewer({});
        });

        $("button.resetorder").on("click", function () {
            $(this).parent().html('<span ondblclick="edit(this,\'shipping\');">双击手动录入单号</span>');
        });

        $("span.seturl").on("click", function () {
            let oid = $(this).attr("oid");
            let rid = $(this).attr("rid");
            layer.prompt({title: '请输入商品连接地址'}, function (url, index) {
                layer.close(index);
                if (url.length == 0) {
                    layer.msg("地址不能为空");
                } else {
                    layer.load(1, {
                        shade: [0.1, '#000'] //0.1透明度的白色背景
                    });
                    $.ajax({
                        type: "post",
                        url: "/backend/orders/seturl",
                        dataType: "json",
                        data: {"oid": oid, "rid": rid, "url": url},
                        error: function () {
                            layer.closeAll();
                            layer.msg("更新失败");
                        },
                        success: function (result) {
                            layer.closeAll();
                            layer.msg("更新成功");
                        },
                    });

                }
            });
        });
    });
    $("#batchship").on("click", function () {
        index = layer.open({
            type: 1,
            title: '请上传批量发货文件',
            skin: 'layui-layer-rim',
            closeBtn: 1,
            area: ['50%', ''],
            shadeClose: true,
            content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><div class="form-group clearfix"><div class="col-sm-2"><span class="control-label">选择文件</span></div><div class="col-sm-6"><div class="input-group"><input id=\'location\' class="form-control" onclick="$(\'#i-file\').click();"><label class="input-group-btn"><input type="button" id="i-check" value="浏览文件" class="btn btn-primary" onclick="$(\'#i-file\').click();"></label><input type="file" name="file" id="i-file"  accept=".xls, .xlsx" onchange="$(\'#location\').val($(\'#i-file\').val());" style="display: none"></div></div></div><div class="form-group clearfix"><button id="actbatchship" class="btn btn-flat btn-success">批量发货提交</button></div></div></div>'
        });
    });
    $("body").on("click", "#actbatchship", function () {
        layer.closeAll();
        filename = $("#i-file").val();
        if (!filename) {
            layer.msg("没有选择批发发货文件");
        } else {
            shadow = layer.load(1, {
                shade: [0.1, '#000']
            });
            var type = "file";
            var formData = new FormData();
            formData.append(type, $("#i-file")[0].files[0]);
            $.ajax({
                type: "post",
                url: "/backend/orders/getxlsxlist",
                data: formData,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (data) {
                    layer.closeAll();
                    if (data["data"].length == 0) {
                        layer.msg("发货列表为空");
                    } else {
                        total = data["data"].length;
                        // layer.msg("共检测到 "+total+" 条发货记录");
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-molv', //样式类名
                            closeBtn: 0, //不显示关闭按钮
                            anim: 2,
                            shadeClose: false, //开启遮罩关闭
                            content: "<div style='padding:20px 20px;' id='tipmsg'>共检测到 " + total + " 条发货记录</div>"
                        });
                        succcount = 0;
                        failcount = 0;
                        $.each(data["data"], function (index, val) {
                            $.ajax({
                                type: "post",
                                url: "/backend/sites/order/ajaxedit",
                                data: {
                                    "attrName": "shipping",
                                    "newHtml": val[1],
                                    "ordersn": val[0],
                                    "trackurl": val[2]
                                },
                                dataType: "json",
                                success: function (result) {
                                    if (result["status"] == 1) {
                                        succcount++;
                                    } else {
                                        failcount++;
                                    }
                                    $("#tipmsg").text("共 " + total + " 条发货记录,成功 " + succcount + " 条，失败 " + failcount + " 条")
                                }
                            });
                        });
                    }
                }
            });
        }
    });
    $("span.btn-forward").on("click", function () {
        itemid = $(this).attr("itemid");
        email = $(this).attr("mail");
        index = layer.open({
            type: 1,
            title: '给' + itemid + '  邮件回复',
            skin: 'layui-layer-rim',
            closeBtn: 1,
            area: ['50%', ''],
            shadeClose: true,
            content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><div class="form-group"><select name="shopfrom" class="form-control input-sm"><option value="">选择回复邮箱</option><option value="taobao">淘宝</option><option value="1688">1688</option><option value="aliexpress">速卖通</option><option value="amazon">亚马逊</option><option value="weixin">微信</option><option value="other">其它</option></select></div><div class="form-group"><input type="text" name="ordersn" class="form-control input-sm" value="<?php echo $item['email'];?>" disabled></div><div class="form-group"><input type="text" name="buyamount" placeholder="邮件内容" class="form-control input-sm"></div><div class="form-group"><input type="text" name="shipsn" placeholder="输入抄送人(选填)" class="form-control input-sm"><input type="hidden" name="orderid" value="' + itemid + '"/></div><div class="form-group"><button id="actshopping" class="btn btn-flat btn-info">确定提交</button></div></div></div>'
        });
    });
    $("body").on("click", "#actshopping", function () {
        var cid = $("input[name=orderid]").val();
        var source = $("select[name=shopfrom]").val();
        var ordersn = $("input[name=ordersn]").val();
        var shipsn = $("input[name=shipsn]").val();
        var buyamount = $("input[name=buyamount]").val();
        if (source.length == 0) {
            layer.msg("请选择回复邮箱");
            return;
        }
        if (ordersn.length == 0) {
            layer.msg("请输入采购订单号");
            return;
        }
        if (source == "weixin" && parseFloat(buyamount) <= 0) {
            layer.msg("微信订单必须输入采购费用");
            return;
        }
        layer.load(1, {
            shade: [0.1, '#000'] //0.1透明度的白色背景
        });
        $.ajax({
            type: "post",
            url: "/backend/sites/order/ajaxshopping",
            dataType: "json",
            data: {"cid": cid, "source": source, "ordersn": ordersn, "shipsn": shipsn, "buyamount": buyamount},
            error: function () {
                layer.closeAll();
            },
            success: function (result) {
                if (result["status"] == 1) {
                    layer.closeAll();
                    layer.msg("采购成功");
                    $("tr[shopid=" + cid + "] span.label").removeClass("label-success").addClass("label-primary").text("采购中");
                    $("span.shopping-btn[itemid=" + cid + "]").hide();
                } else {
                    layer.closeAll();
                    layer.msg(result["msg"]);
                }
            },
        });
    });
    var order_detail = function (title, oid) {
        layer.open({
            type: 2,
            title: title + ' 订单详情',
            shadeClose: true,
            shade: 0.8,
            area: ['94%', '90%'],
            content: '/backend/sites/order/detail/' + oid
        });
    }
    function edit(obj, attrName) {
        var oldHtml = obj.innerHTML;
        var newobj = document.createElement('input');
        newobj.name = attrName;
        newobj.type = "text";
        newobj.setAttribute("class", "form-control input-sm");
        newobj.value = oldHtml;
        console.log(oldHtml);
        if (oldHtml == "双击添加备注" || oldHtml == "双击手动录入单号") {
            newobj.value = '';
        }
        var cid = $(obj).parent().attr("cid");
        obj.innerHTML = '';
        obj.appendChild(newobj);
        newobj.focus();
        $(newobj).keydown(function (event) {
            if (event.keyCode == 13) {
                $(this).trigger("blur");
            }
        });
        $(newobj).blur(function () {
            newvalue = this.value.trim();
            if (newvalue == "" && attrName == "note") {
                oldHtml = "双击添加备注";
            }
            if ((newvalue == null || newvalue == "") && attrName != "note") {
                obj.innerHTML = oldHtml;
                return false;
            }
            obj.innerHTML = newvalue ? newvalue : oldHtml;
            if (oldHtml != newvalue) {
                $.ajax({
                    type: "post",
                    url: "/backend/sites/order/ajaxedit",
                    dataType: "json",
                    data: {"attrName": attrName, "newHtml": newvalue, "cid": cid},
                    error: function () {
                    },
                    success: function (result) {
                        if (result["status"] != 1) {
                            layer.msg(result["msg"]);
                            obj.innerHTML = oldHtml;
                            return false;
                        }
                    },
                });
            }
        })
    }
    $("span.btn-delete").on("click", function (event) {
        var cid = $(this).attr("itemid");
        var row = $(this).parent().parent();
        layer.confirm("确认要删除吗，删除后会进入询盘垃圾箱？", {title: "确认"}, function (index) {
            $.ajax({
                type: "post",
                url: "/backend/orders/ordersajaxdel",
                dataType: "json",
                data: {"cid": cid},
                error: function () {},
                success: function (result) {
                    if (result["status"] == 1) {
                        row.remove();
                    } else {
                        layer.msg(result["msg"]);
                    }
                },
            });
            layer.close(index);
        });

    });

    $("span.handship").on("click", function () {
        $(this).parent().html('<span ondblclick="edit(this,\'shipping\');">双击手动录入单号</span>');
    });

    $("span#export").on("click", function () {
        layer.confirm("请不要导出所有订单，确认后导出，时间会比较长", {title: "确认导出"}, function (index) {
            layer.close(index);
            var url = window.location.href;
            var newUrl = changeURLArg(url, "export", "1");
            window.location.href = newUrl;
        });
    });
    $("select#pagesize").change(function () {
        pagesize = $("select#pagesize option:selected").val();
        if (pagesize > 0) {
            var url = window.location.href;
            var newUrl = changeURLArg(url, "pagesize", pagesize);
            window.location.href = newUrl;
        }
    });
    function changeURLArg(url, arg, arg_val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
        return url + '\n' + arg + '\n' + arg_val;
    }
</script>
